package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	//工具函数
	funcsMap = template.FuncMap{
		"idltime":    TimeFormat,
		"tolower":    strings.ToLower,
		"addnum":     AddNum,
		"isUpper":    StartWithUppercase,
		"pbFiled":    DealPbStructField,
		"stFieldUp":  StFieldFormat,
		"GetModName": GetModuleName,
		"toJsonStr":  ToJsonStr,
	}
)

var (
	moduleName = ""
)

func PathExits(path string) bool {
	finfo, err := os.Stat(path)
	if err != nil {
		return os.IsExist(err)
	}

	return finfo.IsDir()
}

func FileExits(file string) bool {
	finfo, err := os.Stat(file)
	if err != nil {
		return os.IsExist(err)
	}

	return !finfo.IsDir()
}

func DealInputPath(path string) (string, error) {
	path, err := filepath.Abs(path)
	if err != nil {
		fmt.Printf("Convert %s to Abs path err %v", path, err)
		return "", err
	}

	path = strings.Replace(path, "\\", "/", -1)
	if path[len(path)-1] == '/' {
		path = path[:]
	}
	return path, nil
}

// TimeFormat 生成返回值类型
func TimeFormat() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func AddNum(x, y int) int {
	return x + y
}

// StartWithUppercase 是不是大写开头
func StartWithUppercase(word string) bool {
	if len(word) == 0 {
		return false
	}
	head := word[0]
	if head >= 'A' && head <= 'Z' {
		return true
	}
	return false
}

// DealPbStructField 处理pb结构体的生成规则
func DealPbStructField(field string) string {
	idx := strings.Index(field, "_")
	if idx == -1 {
		return strings.ToUpper(field[:1]) + field[1:]
	}

	fls := strings.Split(field, "_")
	res := ""
	for _, fl := range fls {
		if fl == "" {
			if res == "" {
				res = "X"
			} else {
				res = res + "_"
			}
		} else if (fl[0] >= 'a' && fl[0] <= 'z') || (fl[0] >= 'A' && fl[0] <= 'Z') {
			res = res + strings.ToUpper(fl[:1]) + fl[1:]
		} else {
			res = res + "_" + fl
		}
	}
	return res
}

// StFieldFormat go 语言用大小写来控制 是不是暴露给包外面使用 所以 需要把首字符转换为大写
func StFieldFormat(srcfield string) string {
	idx := strings.Index(srcfield, "_")
	if idx == -1 {
		return strings.ToUpper(srcfield[:1]) + srcfield[1:]
	}

	fls := strings.Split(srcfield, "_")
	res := ""
	for _, fl := range fls {
		if fl == "" {
			if res == "" {
				res = "X"
			} else {
				res = res + "_"
			}
		} else if (fl[0] >= 'a' && fl[0] <= 'z') || (fl[0] >= 'A' && fl[0] <= 'Z') {
			res = res + strings.ToUpper(fl[:1]) + fl[1:]
		} else {
			res = res + "_" + fl
		}
	}
	return res
}

func GetModuleName() string {
	if len(moduleName) != 0 {
		return moduleName + "."
	}
	return ""
}

func ToJsonStr(v interface{}) string {
	ret, err := json.Marshal(v)
	if err != nil {
		return ""
	}
	return string(ret)
}